/**
 * Copyright (C) 2012 Oleg Anastassov <o.anastasov@gmail.com>
 *
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements. See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License. You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package kz.kstu.ent.desktop.ui.dialog.students;

import kz.kstu.ent.app.delegate.api.StudentDelegate;
import kz.kstu.ent.app.delegate.impl.StudentDelegateImpl;
import kz.kstu.ent.business.entity.Student;
import kz.kstu.ent.desktop.components.model.AbstractNumeratedTableModel;
import kz.kstu.ent.desktop.images.GUIFactory;
import kz.kstu.ent.desktop.images.GUIIcon;
import kz.kstu.ent.desktop.ui.dialog.card.StudentCardDialog;
import kz.kstu.ent.desktop.util.GUIUtils;
import kz.kstu.ent.util.StringUtil;

import javax.swing.*;
import javax.swing.table.TableColumn;
import javax.swing.table.TableColumnModel;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.List;

/**
 * Date: 01.09.12
 * Time: 8:01
 *
 * @author Oleg Anastassov
 */
public class AllStudentsDialog extends JDialog {

    private static final String TITLE = "Ученики :: Список учеников";

    private static final int WIDTH = 900;
    private static final int HEIGHT = 600;

    private JTable allStudentsTable;
    private JButton findButton;
    private JTextField surnameTextField;
    private JButton closeButton;
    private JButton addButton;
    private JButton editButton;
    private JButton deleteButton;
    private JPanel rootPanel;
    private JButton clearButton;
    private JButton studentCardButton;

    private AllStudentsTableModel tableModel;

    public AllStudentsDialog() {
        setIconImage(
                GUIFactory.getImage(GUIIcon.STUDENTS)
        );
        tableModel = new AllStudentsTableModel();
    }

    public void initStaticComponents() {
        setContentPane(rootPanel);
        setModal(true);
        setSize(WIDTH, HEIGHT);
        allStudentsTable.setModel(getTableModel());
        setResizable(false);
        allStudentsTable.getTableHeader().setReorderingAllowed(false);
        allStudentsTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        TableColumnModel columnModel = allStudentsTable.getColumnModel();
        TableColumn idColumn = columnModel.getColumn(AbstractNumeratedTableModel.ID_COLUMN_INDEX);
        idColumn.setMinWidth(0);
        idColumn.setMaxWidth(0);
        setTitle(TITLE);

        initIcons();
        initListeners();
    }

    public void initData() {
        StudentDelegate delegate = new StudentDelegateImpl();
        List<Student> students = delegate.findAll(Student.class);
        tableModel.setData(students);
    }

    private AbstractNumeratedTableModel getTableModel() {
        tableModel = new AllStudentsTableModel();
        return tableModel;
    }

    private void initListeners() {
        surnameTextField.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                // on <ENTER>
                find();
            }
        });
        clearButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                surnameTextField.setText(StringUtil.EMPTY_STRING);
                find();
            }
        });
        allStudentsTable.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                super.mouseClicked(e);
                if (e.getButton() == MouseEvent.BUTTON1 && e.getClickCount() == 2) {
                    Student student = getSelectedObject();

                    StudentCardDialog dialog = new StudentCardDialog(student);
                    dialog.initStaticComponents();
                    dialog.initData();
                    GUIUtils.centerAndShow(dialog);
                }
            }
        });
        addButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                EditStudentDialog dialog = new EditStudentDialog(new Student());
                dialog.initStaticComponents();
                dialog.initData();
                GUIUtils.centerAndShow(dialog);
            }
        });
        editButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                Student student = getSelectedObject();

                EditStudentDialog dialog = new EditStudentDialog(student);
                dialog.initStaticComponents();
                dialog.initData();
                GUIUtils.centerAndShow(dialog);
            }
        });
        deleteButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                Student student = getSelectedObject();
                if (student == null) {
                    return;
                }

                try {
                    if (JOptionPane.showConfirmDialog(new JFrame(),
                            "<html><b>Вы действительно хотите удалить запись?</b></html>" + "\n"
                                    + StringUtil.concatenate(
                                    student.getSurname(),
                                    student.getName(),
                                    student.getPatronymic()
                            ),
                            "Удаление информации",
                            JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION) {

                        StudentDelegate delegate = new StudentDelegateImpl();
                        delegate.delete(student);

                        JOptionPane.showMessageDialog(
                                rootPane,
                                "Запись успешно удалена",
                                "Удаление информации", JOptionPane.INFORMATION_MESSAGE
                        );

//                        updateTable();
                    }
                } catch (Exception ex) {
                    JOptionPane.showMessageDialog(
                            rootPane,
                            "Невозможно удалить запись. Значение справочника используется.",
                            "Ошибка удаления", JOptionPane.ERROR_MESSAGE
                    );
                }
            }
        });
        studentCardButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                Student student = getSelectedObject();

                if (student == null) {
                    return;
                }

                StudentCardDialog dialog = new StudentCardDialog(student);
                dialog.initStaticComponents();
                dialog.initData();
                GUIUtils.centerAndShow(dialog);
            }
        });
        findButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                find();
            }
        });
        closeButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                dispose();
            }
        });
    }

    private void initIcons() {
        clearButton.setIcon(
                GUIFactory.getIcon(GUIIcon.CLEAR)
        );
        findButton.setIcon(
                GUIFactory.getIcon(GUIIcon.SEARCH)
        );
        addButton.setIcon(
                GUIFactory.getIcon(GUIIcon.STUDENT_ADD)
        );
        editButton.setIcon(
                GUIFactory.getIcon(GUIIcon.STUDENT_EDIT)
        );
        deleteButton.setIcon(
                GUIFactory.getIcon(GUIIcon.STUDENT_DELETE)
        );
        studentCardButton.setIcon(
                GUIFactory.getIcon(GUIIcon.STUDENT_CARD)
        );
        closeButton.setIcon(
                GUIFactory.getIcon(GUIIcon.CANCEL)
        );
    }

    private void find() {
        StudentDelegate delegate = new StudentDelegateImpl();
        List<Student> resultList;
        String surname = surnameTextField.getText();
        if (!surname.equals(StringUtil.EMPTY_STRING)) {
            resultList = delegate.findBySurname(Student.class, surname);
            tableModel.setData(resultList);
        } else {
            tableModel.setData(delegate.findAll(Student.class));
        }
    }

    private Student getSelectedObject() {
        int index = allStudentsTable.getSelectedRow();
        if (index == -1) {
            return null;
        }
        Long id = (Long) tableModel.getValueAt(index, AbstractNumeratedTableModel.ID_COLUMN_INDEX);
        StudentDelegate delegate = new StudentDelegateImpl();
        return delegate.findById(Student.class, id);
    }

    public JPanel getRootPanel() {
        return rootPanel;
    }

}
